<template>
  <div class="similar">
    <avue-form :option="formOption"
               v-model="obj"
               @submit="handleSubmit"
               @tab-click="handleTabClick">
      <!--<template slot="group1Header" slot-scope="scope">
        <h4>{{scope}}</h4>
      </template>-->
    </avue-form>
  </div>
</template>

<script>
import { addCategoryInfo, editCategoryInfo } from '../../../../../api/category/category'

export default {
  name: 'establishSimilar',
  props: {
    type: {
      request: true,
      type: String
    },
    formData: {
      type: Object
    },
    formOption: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      obj: {}
    }
  },
  watch: {
    formData () {
      this.obj = {}
      setTimeout(() => {
        this.$set(this, 'obj', this.formData)
      }, 10)
    }
  },
  methods: {
    handleSubmit (form, done) {
      const dataForm = {
        tables: []
      }
      Object.keys(this.formData).forEach(key => {
        if (key.indexOf('table') > -1) {
          const index = key.substr(key.length - 1, key.length)
          if (!dataForm.tables[index]) {
            dataForm.tables[index] = {}
          }
          dataForm.tables[index][key.substr(0, key.length - 1)] = form[key]
        } else {
          dataForm[key] = form[key]
        }
      })
      dataForm.tables.map(item => {
        delete item.$tableType
      })

      const requestFunc = this.type === 'add' ? addCategoryInfo(dataForm) : editCategoryInfo(dataForm)

      requestFunc.then(() => {
        // 创建类似
        this.$message.success(this.type === 'add' ? '创建成功！' : '修改成功!')
        this.$emit('handleSuccess')
        done()
      }).catch(() => {
        done()
      })
    },
    handleTabClick (event) {
      this.$message.success(event)
    }
  }
}
</script>

<style lang="scss" scoped>
  .similar {
    max-height: calc(100vh - 220px);
    overflow-y: auto;
    margin-right: -20px;
    padding-right: 20px;
  }
</style>
